local CommonOHOH = _G.CommonOHOH;
local asset_Cfg=CommonOHOH.config.Asset
local Levels_Cfg=CommonOHOH.config.Levels
local LevelBuff_Cfg=CommonOHOH.config.LevelBuff
local Pet_Cfg=CommonOHOH.config.Pet
local Egg_Cfg=CommonOHOH.config.Egg

local M={}

local function FindNearPetId (id,buff)
    local d=math.huge
    local pId=id
    local v=Pet_Cfg[pId].value[1]*buff
    assert(v,"Not PET ID"..id)
    for k,cfg in pairs(Pet_Cfg) do
        local a= math.abs(cfg.value[1]-v)
        if a<d then
            d=a
            pId=cfg.id
        end
    end
    return pId
end

local function FindNearEggId (id,buff)
    local d=math.huge
    local pId=id

    local ecfg=Egg_Cfg[pId]
    assert(ecfg,"Not Egg ID"..id)
    local v=ecfg.expect*buff
    for k,cfg in pairs(Egg_Cfg) do
        local a= math.abs(cfg.expect-v)
        if a<d then
            d=a
            pId=cfg.id
        end
    end
    return pId
end

--获取Item的 key 和Id（key为item类型）
function M.GetKeyAndID(itemId)
    local keyList=string.split(itemId,"_")
    local id=string.gsub(itemId,keyList[1].."_","",1)
    return keyList[1],id
end

--获取数量
function M.GetItemCount(itemId,store)
    assert(itemId,"itemId==NUll")
    assert(store,"store==NUll")
    local key,id=M.GetKeyAndID(itemId)
    -- print("key:",key,"  id ",id)
    local storeData=store:GetData(key)
    assert(storeData,"storeData==NUll,key:"..key)

    local count=nil
    if key=="pets" then
        count= storeData.had[id]
    elseif  key=="trail" then
        count= storeData.had[id]
    elseif  key=="glove" then
        count= storeData.had[id]
    else
        count= storeData[id]
    end
   
    if count==nil then
        return 0
    else
        return count
    end
end

--获取蛋信息
function M.GetEggAllInfo(itemId)
    local list=string.split(itemId,"_")
    local eggId=tonumber(list[2])
    assert(eggId,"eggId==nil")
    local eggCfg=Egg_Cfg[eggId]
    assert(eggCfg,"eggCfg==nil")
    local languageHelper=_G.LanguageHelper
    local PetTool=_G.CommonOHOH.load.PetTool() 
    local GeneralTool=_G.CommonOHOH.load.GeneralTool()
    local PercentList=GeneralTool.GetProbabilityShowPercent(eggCfg.probability)

    local data=CommonOHOH:DeepCopy(eggCfg)
    data["name"]=languageHelper:GetText(eggCfg.name)
    data["PetList"]={}
    for k,petId in pairs(eggCfg.petIds) do
        local i=PetTool.GetPetDataByCfgId(petId)
        local m=PetTool.GetPetModelByCfgId(petId)
        data.PetList[k]={
           info= i,
           model= m,
           percent=PercentList[k]
        }
    end

    return data
end
--根据等级计算奖励
function M.GetRewardByLevel(itemId,count,level)
    local buff=LevelBuff_Cfg[level]
    if not buff then
        -- print("不存在该关卡的奖励倍率:",level)
        -- return itemId,count
        local maxIndex=#LevelBuff_Cfg
        buff=LevelBuff_Cfg[maxIndex] --取最大值
    end

    local key,id=M.GetKeyAndID(itemId)

    if key=="base" and buff[id] then

        local count=math.floor(buff[id]*count)
        -- print("-------id----level-----",buff[id],id,count)
        return itemId, _G.CommonOHOH.load.GeneralTool().DigitsSignificantX(count,2) --整理格式
    elseif key=="pets" then
        local list=string.split(itemId,"_")
        local pid=FindNearPetId(tonumber(list[2]),buff.pets)
        return list[1].."_"..pid.."_"..list[3].."_"..list[4],count
    elseif key=="egg" then
        local list=string.split(itemId,"_")
        local eid=FindNearEggId(tonumber(list[2]),buff.egg)
        return list[1].."_"..eid,count
    end
    return itemId,count
end

function M.SaveData(itemId,store,count)
    assert(itemId,"itemId==NUll")
    assert(store,"store==NUll")
    local key,id=M.GetKeyAndID(itemId)
    local storeData=store:GetData(key)
    assert(storeData,"storeData==NUll,key:"..key)
    if not count then
        count=1
    end
    if key=="pets" or key=="weapon" or key=="trail"then
        if storeData.had[id] then
            storeData.had[id]=storeData.had[id]+count
        else
            storeData.had[id]=count
        end
        if  storeData.had[id]==0 then
            storeData.had[id]=nil
        end
    elseif key=="gamePass" then
        storeData[id]=true
    elseif key=="SkillBall" then
        id=tonumber(id)
        if storeData[id] then
            storeData[id]=storeData[id]+count
        else
            storeData[id]=count
        end
    else
        if storeData[id] then
            storeData[id]=storeData[id]+count
        else
            storeData[id]=count
        end
    end
    return key
end

function M.GetItemShowView(itemId)
    assert(itemId,"itemId==NUll")
    local key,id=M.GetKeyAndID(itemId)
    if key=="pets" then
        return _G.CommonOHOH.load.PetTool().GetPetModelByPetId(id),false

    elseif key=="egg" then
        id=tonumber(id)
        local v=Egg_Cfg[id]
        if v.image then
            return v.image,true
        end
        local egg=_G.CommonOHOH:GetPath_Loop(v.path,workspace)
        return _G.CommonOHOH:GetPath_Loop("e",egg):Clone()
    elseif key=="weapon" then
      return   _G.CommonOHOH.load.WeaponTool().GetIconByItemId()
    end
    return asset_Cfg[itemId].rid,true

end

function M.IsHadEnoughByTable(costdata,datastore)
    for k,v in pairs(costdata) do
        if not  M.IsHadEnough(k,v,datastore) then
            return false
        end
    end
    return true
end
-- 是否有足够的item
function M.IsHadEnough(itemId,count,store)
    assert(itemId,"itemId==NUll")
    assert(store,"store==NUll")
    assert(count,"count==NUll")
    local key,id=M.GetKeyAndID(itemId)
    local storeData=store:GetData(key)
    assert(storeData,"storeData==NUll,key:"..key)
    if key=="pets" or key=="glove" or key=="trail" or  key=="weapon"then
        if storeData.had[id] and  storeData.had[id]>=count then
          return true
        else
            return false
        end

    else
        if storeData[id] and storeData[id]>=count then
            return true
        else
            return false
        end
    end
end

local EffectGui=nil
function M.GetEffectGui()
    if not EffectGui then
        EffectGui= Instance.new("ScreenGui",game.Players.LocalPlayer:WaitForChild("PlayerGui"))
        EffectGui.Name="EffectGui"
        EffectGui.DisplayOrder=5000
        EffectGui.ResetOnSpawn=false
    end
    return EffectGui
end


function M.HurtValue2(count,pos)
    
    -- _G.POOL=_G.client:GetComponent(_G.ClientOHOH.load.Client_GameObjectPoolComponent()); --玩家数据

    -- local root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.cloakValue"):Clone()
    -- root.Parent=M.GetEffectGui()
    -- root.Position=pos
    -- local countLable=root:WaitForChild("BloodLoss")
    -- local animator=countLable:WaitForChild("Animator")
    -- countLable.Text="-"..count
    -- require(animator).NewTween:Play()
    -- game:GetService("Debris"):AddItem(root,5)

    local root=_G.POOL:GetObj("UI.cloakValue")
    root.Visible=true
    root.Parent=M.GetEffectGui()
    root.Position=pos
    local countLable=root:WaitForChild("BloodLoss")
    local animator=countLable:WaitForChild("Animator")
    countLable.Text="-"..count
    require(animator).NewTween:Play()
    delay(3,function()
        _G.POOL:PushObj("UI.cloakValue",root)
    end)
   
end

function M.HurtValue(count,pos)
    -- local root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.HurtValue"):Clone()
    -- root.Parent=M.GetEffectGui()
    -- root.Position=pos
    -- local countLable=root:WaitForChild("BloodLoss")
    -- local animator=countLable:WaitForChild("Animator")
    -- countLable.Text="-"..count
    -- require(animator).NewTween:Play()
    -- game:GetService("Debris"):AddItem(root,5)
    local root=_G.POOL:GetObj("UI.HurtValue")
    root.Visible=true
    root.Parent=M.GetEffectGui()
    root.Position=pos
    local countLable=root:WaitForChild("BloodLoss")
    local animator=countLable:WaitForChild("Animator")
    countLable.Text="-"..count
    require(animator).NewTween:Play()
    delay(5,function()
        _G.POOL:PushObj("UI.HurtValue",root)
    end)
    


end

function M.FlyingItem(itemId,count,pos,sacle,root,notbig)
    if not root then
        if notbig then
            root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.ItemFly"):Clone()
        else
            root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.ItemFly2"):Clone()
        end
    end
    if not sacle then
        sacle=1
    end
    if not pos then
        pos=UDim2.fromScale(0.5,0.5)
    end
    local gui=M.GetEffectGui()

    local icon=root:WaitForChild("Strength")
    local animator=icon:WaitForChild("Animator")
    local countLable=icon:WaitForChild("TextLabel")
    local viewPort=icon:WaitForChild("ViewportFrame")
    local CF=viewPort:WaitForChild("CF")
    root.Parent=gui

    local obj,isImage=M.GetItemShowView(itemId)
    if isImage then
        icon.Image=obj
    else
        icon.Image=""
        if obj:IsA("BasePart") then
            obj.CFrame=CF.Value
            obj.Parent=workspace
            task.wait()
            obj.Parent=viewPort
        else
            obj:SetPrimaryPartCFrame(CF.Value)
            obj.Parent=viewPort

        end

    end
  
    countLable.Text="x"..count
    local size=root.AbsoluteSize*sacle
    root.Size=UDim2.fromOffset(size.X,size.Y)
    root.Position=pos
    require(animator).NewTween:Play()
    game:GetService("Debris"):AddItem(root,5)

end

function M.FlyingItem_1(itemId,count,notbig)
    local root
    if notbig then
        root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.ItemFly"):Clone()
    else
        root=CommonOHOH:GetPath_Loop("ReplicatedStorage.Resource.UI.ItemFly2"):Clone()
    end

    local x1,x2,y1,y2
    local gui=M.GetEffectGui()
    local size=gui.AbsoluteSize
     x2=size.X/4
     x1=-x2
     y2=size.Y/4-size.Y/6
     y1=-size.Y/4-size.Y/6

    root.Parent=gui

    local X=root.AbsolutePosition.X+math.random(x1,x2)
    local Y=root.AbsolutePosition.Y+math.random(y1,y2)
    root.Position=UDim2.fromOffset(X,Y)

    M.FlyingItem(itemId,count,UDim2.fromOffset(X,Y),1,root)

end


--是否为R币购买
function M.IsRubux(itemId)
    local key,id=M.GetKeyAndID(itemId)
    return key=="Rubux"
end



--获取好友增加力量数据
function M.GetAwakeFriend_old(data)
    local FriendData={}
    local userId2Level={}
    for k,v in pairs(data) do
        -- print(k,Levels_Cfg[k])
        local condition=Levels_Cfg[k].needSave
        local power=Levels_Cfg[k].saveReward.base_power
        if v.count>=condition then
            if not FriendData[v.userId] then
                FriendData[v.userId]=power
                userId2Level[v.userId]={}
                userId2Level[v.userId][k]=1
            else
                userId2Level[v.userId][k]= userId2Level[v.userId][k]+1
                FriendData[v.userId]=FriendData[v.userId]+power
            end
        end

        for uid,count in pairs(v.statistics) do
            local ac=math.floor(count/condition)
            if ac>0 then
                if not  FriendData[uid] then
                    userId2Level[v.userId]={}
                    FriendData[uid]=ac*power
                    userId2Level[v.userId][k]=ac
                else
                    FriendData[uid]= FriendData[uid]+ac*power
                    userId2Level[v.userId][k]= userId2Level[v.userId][k]+ac
                end
                
            end
        end
    end

    return FriendData,userId2Level
end

local FirendupgradeCfg=CommonOHOH.config.FirendUpgrade


function M.CreateAwakeFriendObj(base,upgrade,levelId)
   local obj= {
        upgrade=0,
        base=0,
        Level={},
        power=0,
        boost=0,
        nextPower=0,
        upgradePrice=0,
        sellPrice=0,
        

        AddBase=function(this,add)
            this.base=this.base+add
        end,

        AddLevel=function(this,levelId,count)
            count=count or 1
            if  this.Level[levelId] then
                this.Level[levelId] =this.Level[levelId]+count
            else
                this.Level[levelId]=count
            end
        end,

        AddUpgrade=function(this,add)
            this.upgrade=this.upgrade+add
        end,

        UpdBaseByLevel=function(this)
            for lvId,count in pairs(this.Level) do
                this.base=this.base+Levels_Cfg[lvId].saveReward.base_power*count
            end
        end,

        Upd=function(this)

            this.boost=FirendupgradeCfg[this.upgrade].boost
            this.upgradePrice=FirendupgradeCfg[this.upgrade].upgrade
            this.sellPrice=FirendupgradeCfg[this.upgrade].sell
            this.power=(1+this.boost)*this.base
            this.nextPower=math.floor((1+FirendupgradeCfg[this.upgrade+1].boost)*this.base+0.5)

        end
    }
    if base then
        obj:AddBase(base)
    end
    if upgrade then
        obj:AddUpgrade(upgrade)
    end
    if levelId then
        obj:AddLevel(levelId)
    end
    obj:Upd()
    return obj
end

--获取好友增加力量数据
function M.GetAwakeFriend(LevelsData,SellData,UpgradeFriend)
    local FriendData={}
    for k,v in pairs(LevelsData) do
        local condition=Levels_Cfg[k].needSave
        if v.count>=condition then
            if not FriendData[v.userId] then
                FriendData[v.userId]=M.CreateAwakeFriendObj()
            end
            FriendData[v.userId]:AddLevel(k,1)
        end
        for uid,count in pairs(v.statistics) do
            local ac=math.floor(count/condition)
            if ac>0 then
                if not  FriendData[uid] then
                    FriendData[uid]=M.CreateAwakeFriendObj()
                end
                FriendData[uid]:AddLevel(k,ac)
            end
        end
    end

    -- 减去卖掉的关卡信息
    for userId,v in pairs(SellData) do
        for levelId,count in pairs(v) do
            FriendData[userId].Level[levelId]=  FriendData[userId].Level[levelId]-count
            if  FriendData[userId].Level[levelId]<=0 then
                FriendData[userId].Level[levelId]=nil
            end
        end
    end

    for k,v in pairs(FriendData) do
        v:UpdBaseByLevel()
        if v.base>0 then
            local upgrade=UpgradeFriend[k] or 0
            v:AddUpgrade(upgrade)
            v:Upd()
        else
            FriendData[k]=nil
        end

    end
    return FriendData
end


return M